<?php
require_once(CORE_DIR.'Common.php');
require_once(CORE_DIR.'mappers/GroupMapper.php');

class groupModel extends Model{

	function __construct(){
		$this->conn = $this->getConnection();
	}
	
	function addGroup($name){
		$query = "insert into `group` (name)
				  values ('%s')";
		$query = $this->format($query, array($name));
		$this->execute($query);		
		return mysqli_insert_id($this->conn);
	}
	
	function updateGroup($id, $name){
		$query = "update `group` set name='%s' where id=%d";
		$query = $this->format($query, array($name, $id));		
		return $this->execute($query);		
	}	
		
	function deleteGroup($id){
		$query = "delete from `group` where id=%d";
		$query = $this->format($query, array($id));		
		if($this->execute($query))
				return $this->deleteUsersOfGroup($id);
		return false;		
	}		
	
	
	function getGroups(){
		$query = "SELECT * FROM `group` ORDER BY name";		
		return $this->execute($query, new GroupMapper());
	}

	/*grouptouser*/
	function deleteUsersOfGroup($groupId){
		$query = "delete from grouptouser where groupId=%d";
		$query = $this->format($query, array($groupId));
		return $this->execute($query);		
	}
	
	function deleteUserOfGroup($userId){
		$query = "delete from grouptouser where userId=%d";
		$query = $this->format($query, array($userId));		
		return $this->execute($query);		
	}	
	
	function addUserToGroup($groupIds, $userId){
		$groupList = explode("|", $groupIds);
		for ($i = 0; $i < count($groupList); $i++)
		{
			$query = "insert into grouptouser (groupId, userId)
				  values (%d, %d)";
			$query = $this->format($query, array($groupList[$i], $userId));		
			$this->execute($query);
		}		
		return mysqli_insert_id($this->conn);		
	}	
	
	function updateUserOfGroup($groupIds, $userId){		
		$this->deleteUserOfGroup($userId);
		$this->addUserToGroup($groupIds, $userId);
	}	
}
?>
